package com.lottery.pay.Utils.wxUtil;

import com.lottery.pay.Constants.WeixinConstant;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyStore;
import java.util.List;
import java.util.Map;

//@Configuration
//@ImportResource("classpath:spring-mvc.xml")
public class HttpRequest {
	public static final Logger logger = LoggerFactory.getLogger(HttpRequest.class);

//	@Value("${upload.cert.base}")
	private static String uploadCertBase="/home/msty/web/ol/MSTY_APP/";

	/**
	 * 向指定URL发送GET方法的请求
	 * 
	 * @param url
	 *            发送请求的URL
	 * @param param
	 *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return URL 所代表远程资源的响应结果
	 */
	public static String sendGet(String url, String param) {
		String result = "";
		BufferedReader in = null;
		try {
			String urlNameString = url + "?" + param;
			URL realUrl = new URL(urlNameString);
			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			// 设置通用的请求属性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 建立实际的连接
			connection.connect();
			// 获取所有响应头字段
			Map<String, List<String>> map = connection.getHeaderFields();
			// 遍历所有的响应头字段
			for (String key : map.keySet()) {
				System.out.println(key + "--->" + map.get(key));
			}
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			logger.info("result:{}", "发送GET请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 向指定 URL 发送POST方法的请求
	 * 
	 * @param url
	 *            发送请求的 URL
	 * @param param
	 *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return 所代表远程资源的响应结果
	 */
	public static String sendPost(String url, Object param) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(
					new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			logger.info("result:{}", "发送 POST 请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}

	public static String sendPost2(String u, Object param) {
		DataOutputStream out = null;
		BufferedReader in = null;
		String result = "";
		try {
			//创建连接
			URL url = new URL(u);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setRequestMethod("POST");
			connection.setRequestProperty("connection", "keep-alive");
			connection.setConnectTimeout(30000);
			connection.setReadTimeout(30000);
			connection.setUseCaches(false);
			connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
			connection.connect();
			// POST请求
			out = new DataOutputStream(connection.getOutputStream());
			String json = param.toString();
			out.writeChars(json); // 这行是关键我之前写的是 out.write(json.getBytes());
			System.out.println(json);
			out.flush();
			// 读取响应
			in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String lines;
			StringBuffer sb = new StringBuffer("");
			while ((lines = in.readLine()) != null) {
				lines = new String(lines.getBytes(), "utf-8");
				sb.append(lines);
			}
			result=sb.toString();
			//获取响应值，判断是否验证通过
			in.close();
			// 断开连接
			connection.disconnect();
		} catch (Exception e) {
			logger.info("result:{}", "发送 POST 请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 用于发送微信退款请求
	 */

	public static String Post(String xml, String url, boolean isUseCert,
                              String sslcert_path, String mch_id) {
		System.gc(); // 垃圾回收，回收没有正常关闭的http连接

		String result = "";// 返回结果

		HttpURLConnection request = null;
		InputStream response = null;
		OutputStream reqStream = null;

		try {
			/***************************************************************
			 * 下面设置HttpWebRequest的相关属性
			 * ************************************************************/
			if (url.toLowerCase().startsWith("https")) {
				HttpsURLConnection httpsRequest = (HttpsURLConnection) new URL(
						url).openConnection();

				// 是否使用证书
				if (isUseCert) {
					KeyStore ks = KeyStore.getInstance("PKCS12");
					// 从服务器上获取相关证书
					File file = new File(uploadCertBase + sslcert_path);
					InputStream inputStream = new FileInputStream(file);
					logger.info("inputStream={}", inputStream);
					if (inputStream != null) {
						// ks.load(inputStream, mch_id.toCharArray());
						ks.load(inputStream, mch_id.toCharArray());
						KeyManagerFactory kmf = KeyManagerFactory
								.getInstance("SunX509");
						kmf.init(ks, mch_id.toCharArray());
						SSLContext sc = SSLContext.getInstance("SSL");
						sc.init(kmf.getKeyManagers(), null, null);
						httpsRequest.setSSLSocketFactory(sc.getSocketFactory());
					}
				}
				request = httpsRequest;
			} else {
				request = (HttpURLConnection) new URL(url).openConnection();
			}

			request.setRequestMethod("POST");
			request.setDoOutput(true);

			// 设置POST的数据类型和长度
			request.addRequestProperty("Content-Type", "text/xml");
			byte[] data = xml.getBytes("UTF-8");

			// 往服务器写入数据
			reqStream = request.getOutputStream();
			reqStream.write(data, 0, data.length);

			// 获取服务端返回
			response = request.getInputStream();

			StringBuffer sb = new StringBuffer();
			byte[] d = new byte[1024];

			while (response.read(d) != -1) {
				sb.append(new String(d, 0, response.read(d), "UTF-8"));
			}

			result = sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.toString());
		} finally {
			// 关闭连接和流
			if (reqStream != null) {
				try {
					reqStream.close();
				} catch (IOException e) {
				}
			}
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
				}
			}
		}
		return result;
	}

	public static String httpClient(String xml, String url,
                                    String sslcert_path, String mch_id) {
		SSLContext sslcontext = null;
		String result = "";
		// 阿里云上获取证书
		File file = new File(uploadCertBase + sslcert_path);
//		logger.info("file={},uploadCertBase={},sslcert_path={}",file,uploadCertBase,sslcert_path);
//		 获取本地证书
//		File file = new File("D:\\workingSpace\\unique\\spv-service\\service-back-end\\service-user\\src\\main\\java\\cn\\superv\\app\\service\\weixin\\control\\cert\\"+sslcert_path);
		if (!file.exists()) {
			result = WeixinConstant.CERT_IS_NOT_EXISTS;
			logger.info("result={}", result);
			return result;
		}
		try {
			// File file = new File(uploadCertBase + sslcert_path);
			InputStream inputStream = new FileInputStream(file);
			logger.info("inputStream={}", inputStream);
			// 指定PKCS12的密码(商户ID)
			KeyStore keyStore = KeyStore.getInstance("PKCS12");
			keyStore.load(inputStream,
					mch_id.toCharArray());
			sslcontext = SSLContexts.custom()
					.loadKeyMaterial(keyStore, mch_id.toCharArray()).build();
		} catch (Exception e) {
			e.printStackTrace();
			// instream.close();
		}
		SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
				sslcontext);
		// 设置httpclient的SSLSocketFactory
		CloseableHttpClient httpclient = HttpClients.custom()
				.setSSLSocketFactory(sslsf).build();
		try {
			HttpPost httpost = new HttpPost(url); // 设置响应头信息
			httpost.addHeader("Connection", "keep-alive");
			httpost.addHeader("Accept", "*/*");
			httpost.addHeader("Content-Type",
					"application/x-www-form-urlencoded; charset=UTF-8");
			httpost.addHeader("Host", "api.mch.weixin.qq.com");
			httpost.addHeader("X-Requested-With", "XMLHttpRequest");
			httpost.addHeader("Cache-Control", "max-age=0");
			httpost.addHeader("User-Agent",
					"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
			httpost.setEntity(new StringEntity(xml, "UTF-8"));
			CloseableHttpResponse response = httpclient.execute(httpost);
			try {
				HttpEntity entity = response.getEntity();
				result = EntityUtils.toString(response.getEntity(), "UTF-8");
				EntityUtils.consume(entity);
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				response.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				httpclient.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		logger.info("result={}", result);
		return result;
	}
}
